import React from 'react'
import { Button, Card, Col, Row, Typography, Image } from 'antd'
import moment from 'moment'
import { API } from '../../config';
// import Link from 'antd/lib/typography/Link'
import { Link } from 'react-router-dom'
import {addItem} from '../../helpers/cart';
import { useDispatch } from 'react-redux';
import { push } from 'connected-react-router';
const { Title, Paragraph } = Typography


function ProductItem({product, imgStyle, showView=true, showCart=true}) {
  // console.log(product)
  // console.log(product._id)
  const { category, createdAt, description, name, price, sold, _id } = product
  const showButtons = () => {
    const buttons = []
    if (showView) buttons.push(
    <Button type='link'>
      <Link to={`/productdetail/${_id}`}>查看详情</Link>
    </Button>)
    if (showCart) buttons.push(<Button onClick={addToCart} type='link'>加入购物车</Button>)
    return buttons
  }
  const dispatch = useDispatch()
  const addToCart = () => {
    addItem(product, () => {
      dispatch(push('/cart'))
    })
  }
  return (
    <Card
      style={imgStyle}
      cover={
        <Image
          // style={imgStyle}
          alt="example"
          src={`${API}/product/photo/${_id}`}
        />
      }
      actions={showButtons()}
    >
      <Title level={5}>{name}</Title>
      <Paragraph ellipsis={{rows: 2}}>{description}</Paragraph>
      <Row>
        <Col span={12}>销量：{sold}</Col>
        <Col span={12}>价格：{price}</Col>
      </Row>
      <Row>
        <Col>所属分类: {category.name}</Col>
      </Row>
      <Row>
        <Col>上架时间：{moment(createdAt).format ('YYYY-MM-DD')}</Col>
      </Row>
    </Card>
  )
}

export default ProductItem
